
import { Map, View, Feature } from 'ol'
import TileLayer from 'ol/layer/Tile'
import Vector from 'ol/layer/Vector'
import TileWMS from 'ol/source/TileWMS'
import VectorSource from 'ol/source/Vector'
import _ from 'lodash'
import { Style, Fill, Stroke, Icon, Text } from 'ol/style'
import { Point, Polygon, LineString } from 'ol/geom'

import defaultIcon from '../icon/default.png'

/**
 * 创建要素
 * @author suzh
 * @param {*} type 创建要素类型，点：Point，线:LineString,面:Polygon
 * @param {*} geom  创建要素的坐标集合，点:[123,22],线:[[123,22],[123,23]],面:[123,22]
 * @param {*} style 创建要素的样式
 * @param {*} properties 创建要素的属性
 * @param {*} id 创建要素的id，用于代替ol_uid
 */
export const createFeature = (type, geom, style, properties, id) => {
    let feature
    if (type === 'Point') {
        feature = new Feature({
            geometry: new Point(geom)
        })
    }
    if (type === 'LineString') {
        feature = new Feature(
            new LineString(geom, 'XY')
        )
    }
    if (type === 'Polygon') {
        feature = new Feature(
            new Polygon([JSON.parse(polygondata.geom)])
        )
    }
    if (feature && style) {
        feature.setStyle(style)
    }
    if (feature && properties) {
        feature.properties = properties
    }
    if (feature && id) {
        feature.ol_uid = id
    }
    return feature
}

/**
 * 往图层添加要素
 * @param {*} layer 
 * @param {*} feature 
 */
export const addFeature = (layer, feature) => {
    if (!layer.getSource()) {
        return;
    }
    layer.getSource().addFeature(feature);
}

/**
 * 移除图层的某个要素
 * @param {*} layer 
 * @param {*} feature 
 */
export const removeFeature = (layer, feature) => {
    if (!layer || layer === null || !layer.getSource() || !feature || feature === null || layer.getSource().getFeatureByUid(feature.ol_uid) == null) {
        return;
    }
    layer.getSource().removeFeature(feature);
}

/**
 * 移除图层的所有要素
 * @param {*} layer 
 */
export const removeAllFeature = (layer) => {
    if (!layer.getSource()) {
        return;
    }
    layer.getSource().clear();
}

/**
 * 根据layerId判断图层是否已经存在
 * @param {*} map 地图容器
 * @param {*} layerId 图层的layerId属性
 * @returns {*} layer 返回图层对象，若没有，则返回undefined
 */
export const isLayerExitByLayerId = (map, layerId) => {
    let layers = map.getLayers();
    let layer;
    for (let i = 0; i < layers.getArray().length; i++) {
        let _layerId = layers.getArray()[i].layerId;
        if (_layerId === layerId) {
            layer = layers.getArray()[i]
        }
    }
    return layer;
}

/**
 * 要素高亮显示
 * @author suzh
 * @param {*} map 地图容器
 * @param {*} feature 需要高亮的要素
 */
export const highlightFeature = (map, feature, img) => {
    let highlightLayer = isLayerExitByLayerId(map, "highlightLayer");
    let hightStyle = new Style({
        stroke: new Stroke({
            color: "rgba(190, 123, 123, 0.6)",
            width: 15
        }),
        fill: new Fill({
            color: "rgba(190, 123, 123, 0.6)"
        }),
    });
    //高亮图层不存在，就新建一个高亮图层
    if (!highlightLayer) {
        let imgUrl = img || defaultIcon
        //高亮样式设置
        hightStyle = new Style({
            stroke: new Stroke({
                color: "rgba(190, 123, 123, 0.6)",
                width: 15
            }),
            fill: new Fill({
                color: "rgba(190, 123, 123, 0.6)"
            }),
            image: new Icon({
                anchor: [0.5, 500],
                anchorXUnits: 'fraction',
                anchorYUnits: 'pixels',
                src: imgUrl,
                scale: 0.1
            })
        })
        //高亮风格的图层：
        highlightLayer = new Vector({
            source: new VectorSource(),
            style: hightStyle
        });
        highlightLayer.layerId = "highlightLayer";
        map.addLayer(highlightLayer);
    } else {
        if (img) {
            //高亮样式设置
            hightStyle = new Style({
                stroke: new Stroke({
                    color: "rgba(190, 123, 123, 0.6)",
                    width: 15
                }),
                fill: new Fill({
                    color: "rgba(190, 123, 123, 0.6)"
                }),
                image: new Icon({
                    anchor: [0.5, 46],
                    anchorXUnits: 'fraction',
                    anchorYUnits: 'pixels',
                    src: img,
                    scale: 1
                })
            })
            highlightLayer.setStyle(hightStyle);
        }else {
            highlightLayer.setStyle(hightStyle);
        }
    }
    let hFeature = _.cloneDeep(feature)
    //如果没有需要高亮的要素，则移除所有当前高亮的要素
    if (!hFeature) {
        //移除高亮图层里面所有要素
        highlightLayer.getSource().clear();
        return;
    } else {
        hFeature.setStyle(undefined);
        hFeature.isHighlightFeature = true;
    }
    //移除高亮图层里面所有要素
    removeAllFeature(highlightLayer);
    //往高亮图层添加要素
    addFeature(highlightLayer, hFeature);
}

/**
 * 高亮要素集合
 * @param {*} map 
 * @param {*} features 
 */
export const highlightFeatures = (map, features, img) => {
    if (!features || !features instanceof Array || features.length === 0) {
        return;
    }
    let highlightLayer = isLayerExitByLayerId(map, "highlightLayer");
    //高亮图层不存在，就新建一个高亮图层
    if (!highlightLayer) {
        let imgUrl = img || defaultIcon
        //高亮样式设置
        let hightStyle = new Style({
            stroke: new Stroke({
                color: "rgba(190, 123, 123, 0.6)",
                width: 15
            }),
            fill: new Fill({
                color: "rgba(190, 123, 123, 0.6)"
            }),
            image: new Icon({
                anchor: [0.5, 46],
                anchorXUnits: 'fraction',
                anchorYUnits: 'pixels',
                src: imgUrl,
                scale: 1
            })
        })
        //高亮风格的图层：
        highlightLayer = new Vector({
            source: new VectorSource(),
            style: hightStyle
        });
        highlightLayer.layerId = "highlightLayer";
        map.addLayer(highlightLayer);
    } else {
        if (img) {
            //高亮样式设置
            let hightStyle = new Style({
                stroke: new Stroke({
                    color: "rgba(190, 123, 123, 0.6)",
                    width: 15
                }),
                fill: new Fill({
                    color: "rgba(190, 123, 123, 0.6)"
                }),
                image: new Icon({
                    anchor: [0.5, 46],
                    anchorXUnits: 'fraction',
                    anchorYUnits: 'pixels',
                    src: img,
                    scale: 1
                })
            })
            highlightLayer.setStyle(hightStyle);
        }else {
            highlightLayer.setStyle(undefined);
        }
    }
    highlightLayer.getSource().clear();
    features.forEach(element => {
        let hElement = _.cloneDeep(element);
        hElement.setStyle(undefined);
        hElement.isHighlightFeature = true;
        addFeature(highlightLayer, hElement);
    });
}

/**
 * 移除高亮的要素
 * @param {*} map 
 * @param {*} feature 
 */
export const removeHighlightFeature = (map, feature) => {
    let highlightLayer = isLayerExitByLayerId(map, "highlightLayer");
    if (!highlightLayer) {
        return;
    }
    removeFeature(highlightLayer, feature);
}

/**
 * 移除所有高亮要素
 * @param {*} map 
 * @param {*} feature 
 */
export const removeAllHighlightFeature = (map, feature) => {
    let highlightLayer = isLayerExitByLayerId(map, "highlightLayer");
    if (!highlightLayer) {
        return;
    }
    removeAllFeature(highlightLayer);
}

/**
 * 根据x，y坐标定位
 * @param {*} map 
 * @param {*} x 
 * @param {*} y 
 */
export const localToXY = (map, x, y) => {
    let view = map.getView();
    let feature = new Feature({
        geometry: new Point([x, y])
    })
    let polygon = feature.getGeometry();
    let size = map.getSize();
    view.fit(polygon, size, { padding: [170, 50, 30, 150] });
}